/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved. distributed with this file and
 * available online at
 */
package com.lap.auth.adapter.driving.persistence.region.repository;

import com.lap.auth.adapter.driving.persistence.region.RegionConverter;
import com.lap.auth.adapter.driving.persistence.region.mapper.RegionMapper;
import com.lap.auth.adapter.driving.persistence.region.po.RegionPo;
import com.lap.auth.domain.region.Region;
import com.lap.auth.domain.region.repository.RegionRepository;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class RegionRepositoryImpl implements RegionRepository {

  private final RegionConverter converter;
  private final RegionMapper regionMapper;

  @Override
  public Integer save(Region region) {
    RegionPo regionPo = converter.toPo(region);
    if (region.isNew()) {
      regionMapper.insert(regionPo);
      return regionPo.getId();
    }
    return regionMapper.updateById(regionPo);
  }

  @Override
  public List<Region> findByPid(Integer pid) {
    List<RegionPo> allList = regionMapper.selectByPid(pid);
    return converter.toDomains(allList);
  }

  @Override
  public Optional<Region> findById(Integer id) {
    var regionDO = regionMapper.selectById(id);
    return Optional.ofNullable(converter.toDomain(regionDO));
  }

  @Override
  public int deleteById(Integer id) {
    return regionMapper.deleteById(id);
  }
}
